import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import { TimeshareData } from '../types';
import { Card, DatePicker, Spin, message } from 'antd';
import { WeightAPI } from '../services/api';
import moment from 'moment';

interface TimeshareChartProps {
  height?: number;
  className?: string;
}

const TimeshareChart: React.FC<TimeshareChartProps> = ({ height = 400, className }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);
  const [loading, setLoading] = useState(false);
  const [selectedDate, setSelectedDate] = useState<moment.Moment>(moment());
  const [timeshareData, setTimeshareData] = useState<TimeshareData | null>(null);

  // 初始化图表
  const initChart = () => {
    if (!chartRef.current) return;

    if (chartInstance.current) {
      chartInstance.current.dispose();
    }

    chartInstance.current = echarts.init(chartRef.current, 'dark');
    
    const handleResize = () => {
      chartInstance.current?.resize();
    };
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  };

  // 获取图表配置
  const getChartOption = () => {
    if (!timeshareData || timeshareData.records.length === 0) {
      return {
        backgroundColor: '#0a0e1b',
        title: {
          text: '暂无数据',
          left: 'center',
          top: 'center',
          textStyle: { color: '#999' }
        }
      };
    }

    const records = timeshareData.records;
    
    // 准备数据
    const timeData = records.map(record => record.time);
    const weightData = records.map(record => record.weight);

    return {
      backgroundColor: '#0a0e1b',
      title: {
        text: `${timeshareData.date} 体重分时图`,
        left: 'left',
        textStyle: { color: '#fff', fontSize: 16 }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'cross' },
        backgroundColor: '#1a1a1a',
        borderColor: '#555',
        textStyle: { color: '#fff' },
        formatter: function(params: any) {
          const point = params[0];
          const record = records[point.dataIndex];
          return `
            <div style="padding: 8px;">
              <div style="font-weight: bold; margin-bottom: 5px;">${point.axisValue}</div>
              <div>真实体重: ${record.weight}kg</div>
              <div>记录类型: ${getRecordTypeText(record.record_type)}</div>
              ${record.note ? `<div>备注: ${record.note}</div>` : ''}
            </div>
          `;
        }
      },
      grid: {
        left: '8%',
        right: '8%',
        top: '15%',
        bottom: '15%'
      },
      xAxis: {
        type: 'category',
        data: timeData,
        axisLine: { lineStyle: { color: '#777' } },
        axisLabel: { 
          color: '#999',
          formatter: (value: string) => {
            // 格式化时间显示
            const time = moment(value, 'HH:mm:ss');
            return time.format('HH:mm');
          }
        },
        splitLine: { show: false }
      },
      yAxis: [
        {
          type: 'value',
          name: '体重(kg)',
          nameTextStyle: { color: '#999' },
          axisLine: { lineStyle: { color: '#777' } },
          axisLabel: { 
            color: '#999',
            formatter: (value: number) => `${value.toFixed(1)}kg`
          },
          splitLine: { lineStyle: { color: '#333' } },
          // 动态计算Y轴范围，让体重变化更明显
          min: (value: any) => {
            if (weightData.length === 0) return 0;
            const minWeight = Math.min(...weightData);
            return Math.floor(minWeight - 0.5); // 向下取整，留出0.5kg的边距
          },
          max: (value: any) => {
            if (weightData.length === 0) return 100;
            const maxWeight = Math.max(...weightData);
            return Math.ceil(maxWeight + 0.5); // 向上取整，留出0.5kg的边距
          },
          interval: 0.1 // 设置刻度间隔为0.1kg，让变化更明显
        }
      ],
      series: [
        {
          name: '真实体重',
          type: 'line',
          data: weightData,
          smooth: false, // 改为直线，让变化更明显
          symbol: 'circle',
          symbolSize: 10, // 增大标记点
          lineStyle: { color: '#00da3c', width: 3 }, // 加粗线条
          itemStyle: { color: '#00da3c' },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(0, 218, 60, 0.4)' },
                { offset: 1, color: 'rgba(0, 218, 60, 0.1)' }
              ]
            }
          },
          // 添加数据标签，显示具体体重值
          label: {
            show: true,
            position: 'top',
            formatter: (params: any) => `${params.value}kg`,
            color: '#00da3c',
            fontSize: 10,
            fontWeight: 'bold'
          }
        }
      ],
      legend: {
        data: ['真实体重'],
        top: 'bottom',
        textStyle: { color: '#999' }
      },
      dataZoom: [
        {
          type: 'inside',
          start: 0,
          end: 100
        }
      ]
    };
  };

  // 获取记录类型文本
  const getRecordTypeText = (type: string) => {
    const typeMap: { [key: string]: string } = {
      'morning': '🌅 早晨',
      'evening': '🌙 晚上',
      'anytime': '⏰ 随时'
    };
    return typeMap[type] || type;
  };

  // 加载分时数据
  const loadTimeshareData = async (date: string) => {
    setLoading(true);
    try {
      const response = await WeightAPI.getTimeshareData(date);
      
      if (response.success && response.data) {
        setTimeshareData(response.data);
      } else {
        message.error(response.error || '获取分时数据失败');
        setTimeshareData(null);
      }
    } catch (error: any) {
      message.error(error.error || '网络错误');
      setTimeshareData(null);
    } finally {
      setLoading(false);
    }
  };

  // 更新图表
  useEffect(() => {
    if (chartInstance.current) {
      const option = getChartOption();
      chartInstance.current.setOption(option);
    }
  }, [timeshareData]);

  // 日期变更
  useEffect(() => {
    loadTimeshareData(selectedDate.format('YYYY-MM-DD'));
  }, [selectedDate]);

  // 初始化图表
  useEffect(() => {
    const cleanup = initChart();
    return cleanup;
  }, []);

  return (
    <Card
      className={className}
      title="分时图"
      extra={
        <DatePicker
          value={selectedDate}
          onChange={(date) => date && setSelectedDate(date)}
          allowClear={false}
          style={{ width: 140 }}
        />
      }
      bodyStyle={{ padding: '10px' }}
      headStyle={{ 
        backgroundColor: '#1a1a1a', 
        borderBottom: '1px solid #333',
        color: '#fff'
      }}
    >
      <Spin spinning={loading}>
        {/* 图表容器 */}
        <div 
          ref={chartRef} 
          style={{ 
            width: '100%', 
            height: height,
            backgroundColor: '#0a0e1b'
          }} 
        />

        {/* 数据统计面板 */}
        {timeshareData && timeshareData.records.length > 0 && (
          <div style={{
            marginTop: '16px',
            padding: '16px',
            backgroundColor: 'rgba(26, 26, 46, 0.8)',
            border: '1px solid #2d4a6b',
            borderRadius: '8px',
            color: '#fff'
          }}>
            <div style={{ 
              display: 'grid', 
              gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))',
              gap: '16px',
              marginBottom: '16px'
            }}>
              <div>
                <div style={{ color: '#999', fontSize: '12px', marginBottom: '4px' }}>当日记录</div>
                <div style={{ color: '#00da3c', fontSize: '18px', fontWeight: 'bold' }}>
                  {timeshareData.records.length}次
                </div>
              </div>
              <div>
                <div style={{ color: '#999', fontSize: '12px', marginBottom: '4px' }}>体重范围</div>
                <div style={{ color: '#fff', fontSize: '18px', fontWeight: 'bold' }}>
                  {Math.min(...timeshareData.records.map(r => r.weight)).toFixed(1)} - {Math.max(...timeshareData.records.map(r => r.weight)).toFixed(1)}kg
                </div>
              </div>
              <div>
                <div style={{ color: '#999', fontSize: '12px', marginBottom: '4px' }}>变化幅度</div>
                <div style={{ color: '#ec0000', fontSize: '18px', fontWeight: 'bold' }}>
                  {(Math.max(...timeshareData.records.map(r => r.weight)) - Math.min(...timeshareData.records.map(r => r.weight))).toFixed(1)}kg
                </div>
              </div>
              <div>
                <div style={{ color: '#999', fontSize: '12px', marginBottom: '4px' }}>平均体重</div>
                <div style={{ color: '#1890ff', fontSize: '18px', fontWeight: 'bold' }}>
                  {(timeshareData.records.reduce((sum, r) => sum + r.weight, 0) / timeshareData.records.length).toFixed(1)}kg
                </div>
              </div>
            </div>
            
            {/* 体重变化趋势分析 */}
            <div style={{ 
              padding: '12px',
              backgroundColor: 'rgba(15, 15, 35, 0.6)',
              borderRadius: '6px',
              border: '1px solid #2d4a6b'
            }}>
              <div style={{ color: '#999', fontSize: '12px', marginBottom: '8px' }}>📊 体重变化趋势分析</div>
              <div style={{ fontSize: '12px', lineHeight: '1.5', color: '#ccc' }}>
                {(() => {
                  const weights = timeshareData.records.map(r => r.weight);
                  const firstWeight = weights[0];
                  const lastWeight = weights[weights.length - 1];
                  const change = lastWeight - firstWeight;
                  const changeText = change > 0 ? '上升' : change < 0 ? '下降' : '持平';
                  const changeColor = change > 0 ? '#ec0000' : change < 0 ? '#00da3c' : '#999';
                  
                  return (
                    <span>
                      从 <span style={{ color: '#1890ff' }}>{firstWeight}kg</span> 到{' '}
                      <span style={{ color: '#1890ff' }}>{lastWeight}kg</span>，
                      总体趋势 <span style={{ color: changeColor, fontWeight: 'bold' }}>{changeText}</span>
                      {change !== 0 && ` ${Math.abs(change).toFixed(1)}kg`}
                    </span>
                  );
                })()}
              </div>
            </div>
          </div>
        )}
      </Spin>
      
      {/* 显示当日记录统计 */}
      {timeshareData && timeshareData.records.length > 0 && (
        <div style={{ 
          marginTop: '10px', 
          padding: '8px 12px', 
          backgroundColor: '#2a2a2a',
          borderRadius: '4px',
          fontSize: '12px',
          color: '#999'
        }}>
          <span>📊 当日记录: {timeshareData.records.length}次</span>
          <span style={{ margin: '0 16px' }}>
            📈 体重范围: {Math.min(...timeshareData.records.map(r => r.weight)).toFixed(1)} - {Math.max(...timeshareData.records.map(r => r.weight)).toFixed(1)}kg
          </span>
          <span>
            🔄 变化幅度: {(Math.max(...timeshareData.records.map(r => r.weight)) - Math.min(...timeshareData.records.map(r => r.weight))).toFixed(1)}kg
          </span>
        </div>
      )}
    </Card>
  );
};

export default TimeshareChart;
